﻿using System;
using System.IO;
using IWshRuntimeLibrary;

namespace PCL.Core.IO;

public static class Files
{
    /// <summary>
    /// 在指定路径创建一个指向目标文件的 .lnk 快捷方式。
    /// </summary>
    /// <param name="shortcut">要创建的快捷方式完整路径，建议以 ".lnk" 结尾</param>
    /// <param name="target">被指向的目标文件或可执行程序路径</param>
    /// <param name="arguments">启动时的命令行参数</param>
    /// <param name="workingDirectory">快捷方式的起始目录</param>
    /// <param name="description">快捷方式说明</param>
    /// <param name="icon">自定义图标，格式 "图标文件路径,索引"</param>
    // Partly generated by o4-mini-high (20250719)
    public static void CreateShortcut(
        string shortcut,
        string target,
        string? arguments = null,
        string? workingDirectory = null,
        string? description = null,
        string? icon = null)
    {
        if (string.IsNullOrWhiteSpace(shortcut))
            throw new ArgumentException("shortcutPath 不能为空", nameof(shortcut));
        if (string.IsNullOrWhiteSpace(target))
            throw new ArgumentException("targetFilePath 不能为空", nameof(target));

        // 确保目录存在
        var dir = Path.GetDirectoryName(shortcut);
        if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) Directory.CreateDirectory(dir);

        // 与 WshShell 交互
        var shell = new WshShell();
        var link = (IWshShortcut)shell.CreateShortcut(shortcut)!;

        // 设置属性
        link.TargetPath = target;
        if (!string.IsNullOrEmpty(arguments)) link.Arguments = arguments;
        if (!string.IsNullOrEmpty(workingDirectory)) link.WorkingDirectory = workingDirectory;
        else link.WorkingDirectory = Path.GetDirectoryName(target) ?? Path.GetPathRoot(target);
        if (!string.IsNullOrEmpty(description)) link.Description = description;
        if (!string.IsNullOrEmpty(icon)) link.IconLocation = icon;

        // 保存 .lnk 文件
        link.Save();
    }
}
